package org.lewis.common.email;

import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.lewis.common.domain.EmailTask;
import org.lewis.common.service.EmailTaskService;
import org.lewis.common.utils.WebUtils;

import com.tocersoft.framework.core.annotations.Component;
import com.tocersoft.framework.core.annotations.Injection;
import com.tocersoft.framework.core.annotations.Scope;
import com.tocersoft.framework.core.beans.ScopeType;

@Component
@Scope(ScopeType.prototype)
public class EmailService {
	
	@Injection
	private EmailTaskService emailTaskService;
	
	
	/**
	 * 发送邮箱
	 * @param type
	 *  邮件类型 @see org.lewis.common.domain.EmailTask.TYPE
	 * @param sendType
	 *  发送类型 @see org.lewis.common.domain.EmailTask.SENDTYPE
	 * @param templateFile
	 *            模板文件
	 * @param emailTitle
	 *            邮件标题
	 * @param emailSendTo
	 *            邮件接收者
	 * @param data
	 *            数据
	 */
	public void sendEmail(String type,String sendType,String templateFile, String emailTitle,String emailSendTo, Map<String, Object> data) {
		Properties props = new Properties();
		VelocityEngine ve = new VelocityEngine();
		String webAppPath = WebUtils.getSession().getServletContext().getRealPath("/");
		// 设置模板的路径
		props.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, webAppPath);
		props.setProperty("input.encoding", "UTF-8");
		props.setProperty("output.encoding", "UTF-8");
		ve.init(props);
		Template t = ve.getTemplate(templateFile, "UTF-8");
		VelocityContext context = new VelocityContext();
		for (Map.Entry<String, Object> entry : data.entrySet()) {
			context.put(entry.getKey(), entry.getValue());
		}
		StringWriter writer = new StringWriter();
		t.merge(context, writer);
		
		EmailTask emailTask=new EmailTask();
		emailTask.setContent(writer.toString());
		emailTask.setSubject(emailTitle);
		emailTask.setReceiver(emailSendTo);
		emailTask.setSendType(sendType);
		emailTask.setType(type);
		
		emailTaskService.addEmailTask(emailTask);
		
		
	}

}
